//
//  JKEssenceViewController.m
//  Baisi
//
//  Created by albert on 16/3/13.
//  Copyright (c) 2016年 albert. All rights reserved.
//

#import "JKEssenceViewController.h"
#import "JKRecommendTagTableViewController.h"
#import "JKBasePostTableViewController.h"
#import "MJRefresh.h"

@interface JKEssenceViewController () <UIScrollViewDelegate, CAAnimationDelegate>
/** 顶部标签按钮下面的红色指示器 */
@property (nonatomic,weak) UIView *indicatorView;
/** 按钮数组 */
@property (nonatomic,weak) NSArray *buttons;
/** 当前选中的标签按钮 */
@property (nonatomic,weak) JKButton *selectedButton;
/** 顶部所有标签的view */
@property (nonatomic,weak) UIView *titlesView;
/** 中间所有的内容 */
@property (nonatomic,weak) UIScrollView *contentView;

/** 上次选中的索引（或者控制器） */
@property (nonatomic, assign) NSInteger lastSeletedIndex;
@end

@implementation JKEssenceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //初始化导航控制器
    [self setupNav];
    
    //初始化子控制器
    [self setupChildVces];
    
    //设置顶部的标签栏
    [self setupTitlesView];
    
    //设置用来切换tableView的scrollView
    [self setupContentView];
    
    //监听tabBar点击的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tabBarSelect:) name:JKTabBarDoubleTapRefreshNotification object:nil];
    
}

//监听tabBar的点击
- (void)tabBarSelect:(NSNotification *)noti{
    
    if (self.navigationController != self.tabBarController.selectedViewController) {
        return;
    }
    
    [self refreshNewData];
    
}

#pragma mark - 初始化子控制器
- (void)setupChildVces{
    
    JKBasePostTableViewController *all = [[JKBasePostTableViewController alloc] init];
    all.title = @"全部";
    all.postType = kPostTypeAll;
    [self addChildViewController:all];
    
    JKBasePostTableViewController *video = [[JKBasePostTableViewController alloc] init];
    video.title = @"视频";
    video.postType = kPostTypeVideo;
    [self addChildViewController:video];
    
    JKBasePostTableViewController *picture = [[JKBasePostTableViewController alloc] init];
    picture.title = @"图片";
    picture.postType = kPostTypePicture;
    [self addChildViewController:picture];
    
    JKBasePostTableViewController *word = [[JKBasePostTableViewController alloc] init];
    word.title = @"段子";
    word.postType = kPostTypeWord;
    [self addChildViewController:word];
    
    JKBasePostTableViewController *voice = [[JKBasePostTableViewController alloc] init];
    voice.title = @"声音";
    voice.postType = kPostTypeVoice;
    [self addChildViewController:voice];
}

#pragma mark - 设置底部的scrollView
- (void)setupContentView{
    //不要自动调整inset
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    //创建scrollView
    UIScrollView *contentView = [[UIScrollView alloc] init];
    [contentView jk_adapt_iOS_11_scrollView];
    contentView.scrollsToTop = NO;
    //要设置frame和控制器的view同样大小
    contentView.frame = self.view.bounds;
    
//    //设置内容间距，上99（64+35），下49间距（tabBar的高度是49）
//    CGFloat topInset = CGRectGetMaxY(self.titlesView.frame);
//    CGFloat bottomInset = self.tabBarController.tabBar.height;
//    contentView.contentInset = UIEdgeInsetsMake(topInset, 0, bottomInset, 0);
    contentView.contentSize = CGSizeMake(contentView.width * self.childViewControllers.count, 0);

    //添加到view,这样写会遮挡住标签栏
    //[self.view addSubview:contentView];
    //改为添加到view的最底部
    [self.view insertSubview:contentView atIndex:0];
    
    //隐藏底部滚动条
    contentView.showsHorizontalScrollIndicator = NO;
    //分页效果
    contentView.pagingEnabled = YES;
    //设置代理
    contentView.delegate = self;
    
    self.contentView = contentView;
    
    [self scrollViewDidEndScrollingAnimation:contentView];
}

#pragma mark - 设置顶部的标签栏
- (void)setupTitlesView{
    
    UIView *containerView = [[UIView alloc] init];
    containerView.width = JKScreenW;
    containerView.height = 35;
    containerView.y = JKNavBarHeight;
    [self.view addSubview:containerView];
    
    UIToolbar *tbar = [[UIToolbar alloc] initWithFrame:containerView.bounds];
    [containerView insertSubview:tbar atIndex:0];
    
    //盛放顶部标签的view
    UIView *titlesView = [[UIView alloc] initWithFrame:containerView.bounds];
    
    //设置颜色透明colorWithAlphaComponent，不要设置view的alpha，否则view的所有子控件都会透明
    titlesView.backgroundColor = nil;//[[UIColor whiteColor] colorWithAlphaComponent:0.7];
    
    [containerView addSubview:titlesView];
    
    self.titlesView = titlesView;
    
    //按钮下面的红色指示器
    UIView *indicatorView = [[UIView alloc] init];
    indicatorView.backgroundColor = [UIColor redColor];
    indicatorView.height = 2;
    indicatorView.y = titlesView.height - indicatorView.height;
    
    //顶部标题按钮
    //使用数组存放标签的文字，这样设置按钮文字的时候，可以直接按顺序从数组取出
//    NSArray *titles = @[@"全dddd部", @"视频", @"图片", @"声音", @"段子"];
    for (NSInteger i = 0; i < self.childViewControllers.count; i++) {
        JKButton *button = [JKButton buttonWithType:(UIButtonTypeCustom)];
        button.height = titlesView.height;
        button.width = titlesView.width / self.childViewControllers.count;
        button.x = i * button.width;
        
        //设置文字
        [button setTitle:[self.childViewControllers[i] title] forState:(UIControlStateNormal)];
        
        //设置普通和选中状态的文字颜色
        [button setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
        [button setTitleColor:[UIColor redColor] forState:(UIControlStateSelected)];
        
        //设置字体大小
        button.titleLabel.font = [UIFont systemFontOfSize:14];
        
        //注册点击事件
        [button addTarget:self action:@selector(titleClick:) forControlEvents:(UIControlEventTouchUpInside)];
        
        //绑定tag
        button.tag = i;
        
        [titlesView addSubview:button];
        
        //默认选中第一个
        if (i == 0) {
            //如果选择调用点击按钮的方法的话，一开始第一个按钮下面的红色指示器会有动画
            
            //所以直接设置号第一个按钮。要让button的frame有值,才能给红色指示器的宽度赋值
            // 1、让titlesView立即布局子控件
            //[titlesView layoutIfNeeded];
            // 2、也可以让按钮的label适应尺寸
            //[button.titleLabel sizeToFit];
            //然后给宽度赋值
            //self.indicatorView.width = button.titleLabel.width;
            
            //也可以直接计算按钮文字所占的宽度
            indicatorView.width = [[self.childViewControllers[i] title] sizeWithAttributes:@{NSFontAttributeName : button.titleLabel.font}].width;
            
            indicatorView.centerX = button.centerX;
            button.selected = YES;
            self.selectedButton = button;
        }
    }
    
    //后添加红色指示器,保证按钮在子控件数组的前面
    [titlesView addSubview:indicatorView];
    
    //将indicatorView赋值给属性
    self.indicatorView = indicatorView;
}

- (void)refreshNewData{
    
    UITableView *tableView = [self.childViewControllers[self.selectedButton.tag] tableView];
    
    [UIView animateWithDuration:0.5 animations:^{
        
        [tableView setContentOffset:CGPointMake(0, -tableView.contentInset.top) animated:NO];
        
    } completion:^(BOOL finished) {
        
        [tableView.mj_header beginRefreshing];
    }];
}

//点击顶部标签按钮
- (void)titleClick:(JKButton *)button{
    //如果点击的是相同的按钮，刷新，返回
    if (self.selectedButton == button) {
        JKLog(@"下拉刷新");
        
        [self refreshNewData];
        
        return;
    }
    
    //设置选中状态
    self.selectedButton.selected = NO;
    button.selected = YES;
    self.selectedButton = button;
    
    //动画显示底部红色指示器
    [UIView animateWithDuration:0.25 animations:^{
        //宽度等于按钮label的宽度
        self.indicatorView.width = button.titleLabel.width;
        
        //中心点x值相等
        //这里就不需要设置了，滑动的时候会设置
        //self.indicatorView.centerX = button.centerX;
    }];
    
    //scrollView滚动
    CGPoint offset = self.contentView.contentOffset;
    offset.x = button.tag * self.contentView.width;
    [self.contentView setContentOffset:offset animated:YES];
}

#pragma mark - 初始化导航控制器
- (void)setupNav{
    //设置导航栏内容
    //通过initWithImage设置的UIImageView的尺寸就和图片的尺寸一样了
    self.navigationItem.titleView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"MainTitle"]];
    
    //设置导航栏leftBarButtonItem为自定义按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:@"MainTagSubIcon" highImage:@"MainTagSubIconClick" target:self action:@selector(tagBtnClick)];
    
    //设置背景颜色
    self.view.backgroundColor = JKGlobalBgColor;
}

/**
 *  点击导航栏左按钮
 */
- (void)tagBtnClick{
    JKRecommendTagTableViewController *tagVc = [[JKRecommendTagTableViewController alloc] init];
    CATransition *transition = [CATransition animation];
    transition.duration = 0.5f;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    transition.delegate = self;
    transition.type = @"push";
    transition.subtype = kCATransitionFromLeft;
    [self.navigationController.view.layer addAnimation:transition forKey:nil];
    [self.navigationController pushViewController:tagVc animated:YES];
}

#pragma mark - <UIScrollViewDelegate>
//called when setContentOffset/scrollRectVisible:animated: finishes. not called if not animating
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    //当前的索引
    NSInteger index = scrollView.contentOffset.x / scrollView.width;
    
    //取出子控制器
    UITableViewController *vc = self.childViewControllers[index];
    //设置x值才能滑动后显示出来，否则默认所有view的x = 0;
    vc.view.x = scrollView.width * index;
    //不设置y值的话，默认y = 20;
    vc.view.y = 0;
    //不设置高度的话，高度默认是屏幕高度 - 20;
    vc.view.height = scrollView.height;
    
//    //最好写在tableViewController内部
//    //设置内容间距，上99（64+35），下49间距（tabBar的高度是49）
//    CGFloat topInset = CGRectGetMaxY(self.titlesView.frame);
//    CGFloat bottomInset = self.tabBarController.tabBar.height;
//    vc.tableView.contentInset = UIEdgeInsetsMake(topInset, 0, bottomInset, 0);
    
    //添加子控制器的view
    [scrollView addSubview:vc.view];
}

//scrollView停止滚动的时候调用，只有这个才能实现滚动切换
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    //调用scrollViewDidEndScrollingAnimation方法
    [self scrollViewDidEndScrollingAnimation:scrollView];
    
    //获取索引
    NSInteger index = scrollView.contentOffset.x / scrollView.width;
    
    //这样写要保证按钮是先添加上去的
    //调用这个方法会出现一些问题。处在第一个tableView向右划，也会下拉刷新
    //[self titleClick:self.titlesView.subviews[index]];
    self.selectedButton.selected = NO;
    self.selectedButton = self.titlesView.subviews[index];
    self.selectedButton.selected = YES;
    
    //动画显示底部红色指示器
    [UIView animateWithDuration:0.25 animations:^{
    
        //宽度等于按钮label的宽度
        self.indicatorView.width = self.selectedButton.titleLabel.width;
        //设置中心点x值，不能省
        self.indicatorView.centerX = self.selectedButton.centerX;
    }];
}

//只要scrollView滚动就会调用这个方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    //按钮的宽度
    CGFloat buttonWidth = self.selectedButton.width;
    
    //scrollView已经偏移的x值 / 能移动的总宽度（取值为0~0.8）
    CGFloat totalScale = scrollView.contentOffset.x / scrollView.contentSize.width;
    
    //设置中心点x值 = 起始位置x值 + 标签栏view总宽度 * 上面的比例
    self.indicatorView.centerX =  buttonWidth * 0.5 + (self.titlesView.width) * totalScale;
    
    
    //两个tableView之间偏移的比例
    
}

@end

#pragma mark - 自定义按钮，去除按钮高亮
@implementation JKButton

//去除按钮高亮
-(void)setHighlighted:(BOOL)highlighted{};

@end
